<template>
  <div ref="editor"  ></div>
</template>

<script>
  /* eslint-disable */
  import $ from 'jquery';

  require('../../../static/umeditor/themes/default/css/umeditor.css');
  require('../../../static/umeditor/umeditor.config.js');
  require('../../../static/umeditor/umeditor.min.js');
  require('../../../static/umeditor/lang/zh-cn/zh-cn.js');

  export default {
    data() {
      return {
        id:'ueditorId'+new Date().getTime(),
        isumeloaded:false,
      };
    },
    props: {
      value: {
        type: String,
        default: null,
      },
      config: {
        type: Object,
        default: {},
      }
    },
    watch: {
      value: function value(val, oldVal) {
        if(!this.isumeloaded){
          return;
        }
        this.editor = UM.getEditor(this.id, this.config);

        var ucontent = this.editor.getContent();
        if (val!=ucontent) {
          this.editor.setContent(val);
        }else if(!val){
          this.editor.setContent('');
        }
      },
    },
    mounted() {
      window.$=$;
      var self=this;
      this.$nextTick(function f1() {
        // 保证 this.$el 已经插入文档
        this.$refs.editor.id = this.id;
        this.editor = UM.getEditor(this.id, this.config);

        this.editor.ready(function f2() {
          if(this.value)
          this.editor.setContent(this.value);
          self.isumeloaded=true;
          this.editor.addListener("contentChange", function () {
            const wordCount = this.editor.getContentLength(true);
            const content = this.editor.getContent();
            const plainTxt = this.editor.getPlainTxt();
            this.$emit('input', { wordCount: wordCount, content: content, plainTxt: plainTxt });
          }.bind(this));

          this.$emit('ready', this.editor);
        }.bind(this));
      });
    },
  };
</script>

<style>
</style>